package org.uim.cricket.analyzer.analyze;

import java.io.IOException;
import java.util.List;
import java.util.Map;

import org.uim.cricket.analyzer.analyze.report.AnalyzerReportable;
import org.uim.cricket.analyzer.analyze.report.XMLAnalyzerReporter;
import org.uim.cricket.entities.MatchPlayer;
import org.uim.cricket.entities.match.CricketMatch;

/**
 * Starting point of analyzing a cricket match for any anomalies.
 * 
 * @author Isuru Madushanka
 *
 */
public class Analyzer {

	private AnalyzerProperties analProperties = null;
	
	private CricketMatch cricketMatch = null;
	private ExecutorAnalyzings executor = null;
	private AnalyzerReportable reporter = null;
	private Map<String, List<MatchPlayer>> playerData = null;
	
	public Analyzer(CricketMatch theMatch) throws IOException {
		this.cricketMatch = theMatch;
		this.analProperties = new AnalyzerProperties();
	}
	
	public void analyze() throws Exception {
		if (executor == null) {
			throw new Exception("ExecutorAnalyzings interface can't be empty!");
		}
		if (reporter == null) {
			throw new Exception("AnalyzerReportable interface can't be empty!");
		}
		
		Alogger.printHeader("Starting Analyzer to analyze " + cricketMatch.getId().getPrefix() + " # " + 
				cricketMatch.getId().getInternationalID() + " ..."); 
		playerData = executor.execute(cricketMatch);
		Alogger.printHeader("Completed Analyzer.");
		
		Alogger.printSubHeader("Reporting analyzer...");
		if (reporter instanceof XMLAnalyzerReporter) {
			((XMLAnalyzerReporter) reporter).setXmlFile(this.generateOutputFilePath(cricketMatch));
		}
		reporter.report(cricketMatch, playerData);
		Alogger.printSubHeader("Completed analyzer reporting.");
		
		Alogger.debug("Quiting.");
	}
	
	private String generateOutputFilePath(CricketMatch match) {
		String filename = this.analProperties.getProperty("output.dir");
		if (filename == null) filename = "";
		if (!filename.endsWith("/")) filename += "/";
		
		String file = match.getId().getPrefix() + "." + match.getId().getInternationalID() + "-analyzer.xml";
		return filename + file;
	}
	
	public void setCricketMatch(CricketMatch cricketMatch) {
		this.cricketMatch = cricketMatch;
	}
	
	public CricketMatch getCricketMatch() {
		return cricketMatch;
	}
	
	public void setExecutor(ExecutorAnalyzings executor) {
		this.executor = executor;
	}
	
	public ExecutorAnalyzings getExecutor() {
		return executor;
	}
	
	public void setReporter(AnalyzerReportable reporter) {
		this.reporter = reporter;
	}
	
	public AnalyzerReportable getReporter() {
		return reporter;
	}

	public Map<String, List<MatchPlayer>> getPlayerData() {
		return playerData;
	}
}
